/*
 * WCILogin.cpp
 *
 *  Created on: Mar 16, 2017
 *      Author: zhangjf
 */

#include <Poco/JSON/Parser.h>
#include <Poco/JSON/Object.h>

using namespace Poco::JSON;

#include "MainApplication.h"
#include "SessionManager.h"
#include "WebCallInterface.h"
#include "WCILogin.h"

WCILogin::WCILogin(Object::Ptr& joParams)
: WebCallInterface("Login", joParams)
{
}

WCILogin::~WCILogin()
{
}

bool WCILogin::process()
{
	bool blRet = false;

	Object joReq;

	joReq.set(_strMethod, _strMethodName);
	joReq.set(_strParams, _joParams);

	std::string strReq = ((DynamicStruct)joReq).toString();
	SessionManager::sendBytes(strReq.data(), strReq.length());

	char buffer[1024];
	UInt32 n = SessionManager::receiveBytes(buffer, sizeof(buffer) - 1);
	std::string strMsg(buffer, n);

	Parser parser;
	Var varResp = parser.parse(strMsg);
	Object::Ptr joResp = varResp.extract<Object::Ptr>();

	if (joResp->has("result") && (joResp->getValue<std::string>("result") == "success"))
	{
		std::string sid = joResp->getValue<std::string>("sid");
		_joResult.set("login", "success");
		_joResult.set("sid", sid);
		blRet = true;
	}
	else
	{
		std::string sid = joResp->getValue<std::string>("sid");
		_joError.set("code", 32100);
		_joError.set("message", joResp->getValue<std::string>("reason"));
	}

	return blRet;
}
